package com.joint.action.com;

import com.joint.action.BaseAction;
import com.joint.util.SHA1;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;
import org.apache.struts2.convention.annotation.ParentPackage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Administrator on 2015/2/10.
 */
@ParentPackage("com")
public class IndexAction extends BaseAction {

    private static String Token = "vzhanqun1234567890";



    public String execute() throws IOException {
        String method = getRequest().getMethod();
        boolean isPostMethod = "POST".equalsIgnoreCase(method);
        String signature = getRequest().getParameter("signature");
        String nonce = getRequest().getParameter("nonce");
        String timestamp = getRequest().getParameter("timestamp");
        String echostr = getRequest().getParameter("echostr");//随机字符串
        if(!isPostMethod){
            List<String> params = new ArrayList<String>();
            params.add(Token);
            params.add(timestamp);
            params.add(nonce);

            Collections.sort(params, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o1.compareTo(o2);
                }
            });

            String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
            if (temp.equals(signature)) {
                getResponse().getWriter().write(echostr);
            }

        }
        return null;
    }
    public void menuApp(){
        WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();

        WxMpServiceImpl wxMpService = new WxMpServiceImpl();

        WxMenu wxMenu = new WxMenu();
        WxMenu.WxMenuButton button = new WxMenu.WxMenuButton();
        button.setType("click");
        button.setName("测试点击");
        button.setUrl("www.baidu.com");

        wxMenu.getButtons().add(button);
        try {
            wxMpService.menuCreate(wxMenu);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

    }
    public String center(){
        return "center";
    }
}
